/**
 * Created by jaliu on 2015/2/28.
 */

'use strict';

angular.module('operationChoujiangLiuchengApp', []).
    controller('liuchengCtrl', ['$scope', '$rootScope', '$location', '$http', function ($scope, $rootScope, $location, $http) {
        $scope.$watch('$viewContentLoaded', function () {
            var params = {};
            if (window.location.pathname) {
                var parts = location.search.substring(1).split('&');
                for (var i = 0; i < parts.length; i++) {
                    var nv = parts[i].split('=');
                    if (!nv[0]) continue;
                    params[nv[0]] = nv[1] || true;
                }
            }

            $.getJSON("http://" + window.location.host + "/getBackOfficeConfigForClient",
                function (data) {
                    var backOfficeHost = data.backOfficeHost;
                    var fastDfsHostIp = data.fastDfsHostIp;
                    initLiucheng(backOfficeHost, fastDfsHostIp);
                }
            );

            var a = Math.random();

            function initLiucheng(backOfficeHost, fastDfsHostIp) {
                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getUserInfo/' + params.userObjId + '/' + params.giftActivityObjId + '?code=' + a, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (result) {
                    $scope.userInfo = result.data;
                    $('.loadPic').hide();
                    $('.loadDiv').hide();
                    if ($scope.userInfo.timePeriodAvailable == null || $scope.userInfo.timePeriodAvailable == '') {
                        $('select[name=selDateTime]').val('16:00 - 17:00');
                        $scope.userInfo.timePeriodAvailable = '16:00 - 17:00';
                    }
                }).error(function () {
                    $('.loadPic').show();
                    $('.loadDiv').show();
                });
            }

        });

        //====================送橙子活动===============================
        $scope.changeUserNameLiuCheng = function () {
            $scope.displayError = false;
        }
        $scope.changePhoneLiuCheng = function () {
            $scope.displayError = false;
        }
        $scope.changeAddressLiuCheng = function () {
            $scope.displayError = false;
        }
        $scope.submit = function (userInfo) {
            if (userInfo.userName == null || userInfo.userName == '') {
                $scope.displayError = true;
                $scope.errorMessage = "请输入姓名";
                return;
            }
            ;
            if (userInfo.phone == null || userInfo.phone == '') {
                $scope.displayError = true;
                $scope.errorMessage = "请输入电话";
                return;
            } else {
                if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(userInfo.phone))) {
                    $scope.displayError = true;
                    $scope.errorMessage = "手机号码不正确";
                    return;
                }
            }
            if (userInfo.roomUnit == null || userInfo.roomUnit == '') {
                $scope.displayError = true;
                $scope.errorMessage = "请输入单元";
                return;
            }
            ;
            if (userInfo.roomNumber == null || userInfo.roomNumber == '') {
                $scope.displayError = true;
                $scope.errorMessage = "请输入房间号";
                return;
            }
            ;

            if (userInfo.timePeriodAvailable == null || userInfo.timePeriodAvailable == '') {
                $scope.displayError = true;
                $scope.errorMessage = "请选择送货时间";
                return;
            }
            ;

            var params = {};
            if (window.location.pathname) {
                var parts = location.search.substring(1).split('&');
                for (var i = 0; i < parts.length; i++) {
                    var nv = parts[i].split('=');
                    if (!nv[0]) continue;
                    params[nv[0]] = nv[1] || true;
                }
            }

            $.getJSON("http://" + window.location.host + "/getBackOfficeConfigForClient",
                function (data) {
                    var backOfficeHost = data.backOfficeHost;
                    var fastDfsHostIp = data.fastDfsHostIp;
                    postLiucheng(backOfficeHost, fastDfsHostIp);
                }
            );

            function postLiucheng(backOfficeHost, fastDfsHostIp) {

                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/doRegisterActivity/' + params.userObjId + '/' + params.giftActivityObjId, userInfo, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.displayMessageBox = true;
                    $scope.displayError = false;
                    $scope.errorMessage = "";
                    $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getUserInfo/' + params.userObjId + '/' + params.giftActivityObjId, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $scope.userInfo = result.data;
                        var height = $(window).scrollTop();
                        $('.join-ok').css({'top': height});
                        $('.join-ok-w').show();
                    }).error(function () {
                        $('.loadPic').show();
                        $('.loadDiv').show();
                    });
                }).error(function () {
                    $scope.displayMessageBox = false;
                    $('.loadPic').show();
                    $('.loadDiv').show();
                });
            }
        };
    }]).
    controller('choujiangCtrl', ['$scope', '$rootScope', '$location', '$http', '$interval', function ($scope, $rootScope, $location, $http, $interval) {

        $scope.$watch('$viewContentLoaded', function () {
            var params = {};
            if (window.location.pathname) {
                var parts = location.search.substring(1).split('&');
                for (var i = 0; i < parts.length; i++) {
                    var nv = parts[i].split('=');
                    if (!nv[0]) continue;
                    params[nv[0]] = nv[1] || true;
                }
            }

            $.getJSON("http://" + window.location.host + "/getBackOfficeConfigForClient",
                function (data) {
                    var backOfficeHost = data.backOfficeHost;
                    var fastDfsHostIp = data.fastDfsHostIp;
                    initChouJiang(backOfficeHost, fastDfsHostIp);
                }
            );

            var code = Math.random();

            function initChouJiang(backOfficeHost, fastDfsHostIp) {
                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/validateUserForLottery/' + params.userObjId + '/' + params.giftActivityObjId + '?code=' + code, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (result) {
                    //获取到抽奖资格信息
                    $scope.userInfoChouJiang = result.data;
                    $scope.userInfoChouJiang.valid = true;

                    $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getLuckyUserList/' + params.giftActivityObjId + '?code=' + code, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {

                        //获取到幸运者列表
                        $scope.luckyUserList = result.data;

                        //幸运者名单
                        $scope.luckyUserList.forEach(function (elem) {

                            //第几周
                            elem.lotteryWeek = elem.week;

                            //抽奖时间
                            //elem.date

                            //幸运者名单
                            elem.uList.forEach(function (tempElem) {

                                if (tempElem.profileImage == null || tempElem.profileImage == '') {
                                    tempElem.profileImage = 'images/choujiang/anonymous.png';
                                } else if (tempElem.profileImage.indexOf('http') != 0) {
                                    tempElem.profileImage = fastDfsHostIp + tempElem.profileImage;
                                }


                                //tempElem.profileImage = 'images/choujiang/anonymous.png';

                                tempElem.userName = tempElem.userName;
                                tempElem.address = tempElem.address;
                                tempElem.roomUnit = tempElem.roomUnit;

                                if (tempElem.prize == 'iphone6') {
                                    tempElem.giftImage = 'images/choujiang/iphone-prize.png'
                                    tempElem.prize = 'iPhone6 ';
                                } else if (tempElem.prize == 'ipad') {
                                    tempElem.giftImage = 'images/choujiang/ipad-prize.png'
                                    tempElem.prize = 'IPAD';
                                } else if (tempElem.prize == 'camera') {
                                    tempElem.giftImage = 'images/choujiang/camera-prize.png'
                                    tempElem.prize = '拍立得 ';
                                } else if (tempElem.prize == 'power') {
                                    tempElem.prize = '小米电源';
                                    tempElem.giftImage = 'images/choujiang/power-prize.png'
                                }

                                tempElem.ranking = tempElem.ranking;
                                tempElem.level = tempElem.level;
                                tempElem.questionCount = tempElem.questionCount;
                            });
                        })

                        ////幸运者名单
                        //$scope.luckyUserList.forEach(function (elem) {
                        //    Date.prototype.format = function (format) {
                        //        var o = {
                        //            "M+": this.getMonth() + 1, //month
                        //            "d+": this.getDate(), //day
                        //            "h+": this.getHours(), //hour
                        //            "m+": this.getMinutes(), //minute
                        //            "s+": this.getSeconds(), //second
                        //            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
                        //            "S": this.getMilliseconds() //millisecond
                        //        }
                        //        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
                        //            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                        //        for (var k in o) if (new RegExp("(" + k + ")").test(format))
                        //            format = format.replace(RegExp.$1,
                        //                RegExp.$1.length == 1 ? o[k] :
                        //                    ("00" + o[k]).substr(("" + o[k]).length));
                        //        return format;
                        //    }
                        //    var TempDate = new Date(elem.lotteryTime);
                        //    TempDate.toLocaleDateString();
                        //    TempDate.format("yyyy-MM-dd");
                        //    elem.lotteryTime = TempDate.format("yyyy-MM-dd");
                        //
                        //    if (elem.profileImage.indexOf('http://') == -1) {
                        //        elem.profileImage = fastDfsHostIp + elem.profileImage;
                        //    }
                        //})

                        //抽奖时间倒计时
                        $interval(callAtInterval, 1000);
                        function callAtInterval() {
                            var timeStart = new Date().getTime();
                            var timeEnd = new Date($scope.userInfoChouJiang.lotteryTime).getTime();
                            var millsecDiff = timeEnd - timeStart; //in milliseconds
                            var secDiff = millsecDiff / 1000; //in seconds
                            var minDiff = millsecDiff / 60 / 1000; //in minutes
                            var hourDiff = millsecDiff / 3600 / 1000; //in hours
                            var humanReadable = {};
                            humanReadable.hours = Math.floor(hourDiff);
                            humanReadable.minutes = Math.floor(minDiff - 60 * humanReadable.hours);
                            humanReadable.seconds = Math.floor(secDiff - 60 * humanReadable.minutes - 60 * 60 * humanReadable.hours);
                            humanReadable.days = Math.floor(humanReadable.hours / 24);
                            $scope.timeToNextLottery = humanReadable.days + ' 天 ' + (humanReadable.hours - humanReadable.days * 24) + ' 小时 ' + humanReadable.minutes + ' 分 ' + humanReadable.seconds + ' 秒';
                        }

                        $('.loadPic').hide();
                        $('.loadDiv').hide();
                    }).error(function () {
                        $('.loadPic').show();
                        $('.loadDiv').show();
                    });
                }).error(function () {
                    $('.loadPic').show();
                    $('.loadDiv').show();
                });
            }
        });

        //====================iPhone抽奖活动==========================

        $scope.changeUserNameChouJiang = function () {
            $scope.displayChouJiangError = false;
        }
        $scope.changePhoneChouJiang = function () {
            $scope.displayChouJiangError = false;
        }
        $scope.changeAddressChouJiang = function () {
            $scope.displayChouJiangError = false;
        }
        $scope.submitChouJiang = function (userInfoChouJiang) {

            if (userInfoChouJiang.userName == null || userInfoChouJiang.userName == '') {
                $scope.displayChouJiangError = true;
                $scope.errorMessageChouJiang = "请输入联系人";
                return;
            }
            ;
            if (userInfoChouJiang.phone == null || userInfoChouJiang.phone == '') {
                $scope.displayChouJiangError = true;
                $scope.errorMessageChouJiang = "请输入联系电话";
                return;
            } else {
                if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(userInfoChouJiang.phone))) {
                    $scope.displayChouJiangError = true;
                    $scope.errorMessageChouJiang = "手机号码不正确";
                    return;
                }
            }
            if (userInfoChouJiang.roomUnit == null || userInfoChouJiang.roomUnit == '') {
                $scope.displayChouJiangError = true;
                $scope.errorMessageChouJiang = "请输入单元";
                return;
            }
            ;

            if (userInfoChouJiang.roomNumber == null || userInfoChouJiang.roomNumber == '') {
                $scope.displayChouJiangError = true;
                $scope.errorMessageChouJiang = "请输入房间号";
                return;
            }
            ;

            var params = {};
            if (window.location.pathname) {
                var parts = location.search.substring(1).split('&');
                for (var i = 0; i < parts.length; i++) {
                    var nv = parts[i].split('=');
                    if (!nv[0]) continue;
                    params[nv[0]] = nv[1] || true;
                }
            }

            $.getJSON("http://" + window.location.host + "/getBackOfficeConfigForClient",
                function (data) {
                    var backOfficeHost = data.backOfficeHost;
                    var fastDfsHostIp = data.fastDfsHostIp;
                    postChouJiang(backOfficeHost, fastDfsHostIp);
                }
            );

            function postChouJiang(backOfficeHost, fastDfsHostIp) {
                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/generateLotteryTicketForUser/' + params.userObjId + '/' + params.giftActivityObjId, userInfoChouJiang, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/validateUserForLottery/' + params.userObjId + '/' + params.giftActivityObjId, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $scope.userInfoChouJiang = result.data;
                    }).error(function () {
                        $('.loadPic').show();
                        $('.loadDiv').show();
                    });
                }).error(function () {
                    $scope.displayMessageBox = false;
                });
            }
        }

        $scope.goPostQuestion = function () {

            var params = {};
            if (window.location.pathname) {
                var parts = location.search.substring(1).split('&');
                for (var i = 0; i < parts.length; i++) {
                    var nv = parts[i].split('=');
                    if (!nv[0]) continue;
                    params[nv[0]] = nv[1] || true;
                }
            }
            if (params.type == 'ios') {
                document.location = "66xiaoqu:Question:ask";
            } else {
                webviewhandle.goToAskQuestion();
            }
        }

        $scope.goAnswerQuestion = function () {

            var params = {};
            if (window.location.pathname) {
                var parts = location.search.substring(1).split('&');
                for (var i = 0; i < parts.length; i++) {
                    var nv = parts[i].split('=');
                    if (!nv[0]) continue;
                    params[nv[0]] = nv[1] || true;
                }
            }
            if (params.type == 'ios') {
                document.location = "66xiaoqu:Question:anwser";
            } else {
                webviewhandle.goToQuestionList();
            }
        }
    }]);




